
<template>
  <view class="uni-container">
    <uni-forms ref="form" v-model="formData" :rules="rules" validateTrigger="bind">
		<uni-forms-item name="room_name" label="名称">
		  <uni-easyinput placeholder="教室名称" v-model="formData.room_name" />
		</uni-forms-item>
		<uni-forms-item name="building" label="教学楼">
		  <uni-easyinput placeholder="教室所在教学楼" v-model="formData.building" />
		</uni-forms-item>
		<uni-forms-item name="type" label="教室类型">
		  <uni-data-checkbox v-model="formData.type" :localdata="formOptions.type_localdata" />
		</uni-forms-item>
		<uni-forms-item name="number" label="容量">
		  <uni-easyinput placeholder="教室容量" type="number" v-model="formData.number" />
		</uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator url="/pages/course/room/list" style="margin-left: 15px;">
            <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import validator from '@/js_sdk/validator/classroom.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'hr-classroom';

  function getValidator(fields) {
    let reuslt = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        reuslt[key] = validator[key]
      }
    }
    return reuslt
  }

  export default {
    data() {
      return {
        formOptions: {
  "type_localdata": [
    {
      "text": "书写墙教室",
      "value": 0
    },
    {
      "text": "实验室",
      "value": 1
    },
    {
      "text": "室内运动场",
      "value": 2
    },
    {
      "text": "室外运动场",
      "value": 3
    },
    {
      "text": "美术教室",
      "value": 4
    },
    {
      "text": "音乐教室",
      "value": 5
    }
  ]
},
        formData: {
  "room_name": "",
  "building": "",
  "type": 0,
  "number": null
},
        rules: {
          ...getValidator(["room_name","building","type","number"])
        }
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      /**
       * 触发表单提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.submit().then((res) => {
          this.submitForm(res)
        }).catch((errors) => {
          uni.hideLoading()
        })
      },

      submitForm(value) {
        // 使用 uni-clientDB 提交数据
        db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateTo({
						url: '/pages/course/room/list'
					}), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>

